<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\model\Comment as CommentModel;
use app\common\model\Room as RoomModel;
use app\common\model\User as UserModel;
use app\common\controller\Backend;
use think\Request;

class Comment extends Backend
{
    //评论列表
    public function index()
    {
        $commentList = CommentModel::select()->toArray();
        $roomList = RoomModel::select()->toArray();
        $roomIdMap = array_column($roomList, 'name', 'id');
        foreach ($commentList as &$comment) {
            $comment['room_name'] = $roomIdMap[$comment['room_id']];
        }
        return $this->fetch('comment/index', ['commentList' => $commentList]);
    }

    //评论编辑
    public function edit(Request $request)
    {
        $comment = CommentModel::findOrEmpty($request->get('id', 0));
        return $this->fetch('comment/edit', [
            'comment' => $comment
        ]);
    }

    //评论保存
    public function save(Request $request)
    {
        try {
            $data = $request->post();
            CommentModel::update($data);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->redirect('index');
    }

    //评论删除
    public function delete(Request $request)
    {
        try {
            CommentModel::destroy($request->get('id'));
        } catch (\Exception $e) {
            $this->error('删除失败');
        }

        $this->success('删除成功');
    }
}
